﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TvTipper.Entities;
using System.Net;
using TvTipper.Core;
using TvTipper.Api;

namespace TvTipper.Controls
{
    public partial class PersonInfoPanel : BaseInfoPanel
    {
        public PersonInfoPanel()
        {
            InitializeComponent();
        }

        protected override void Clear()
        {
            m_pic.Image = null;
            ClearAllTextFields();
        }

        protected override void LoadNewEntity(Entity entity)
        {
            var person = (Person) entity;

            m_bs.DataSource = entity;


            //info
            if (!string.IsNullOrEmpty(person.Info) && person.Info.StartsWith("/m/"))
            {
                m_info.Visible = false;
                m_webInfo.Visible = true;
                var infoUri = string.Format("http://img.freebase.com/api/trans/raw/{0}", person.Info);
                m_webInfo.Navigate(infoUri);
            }
            else
            {
                m_webInfo.Visible = false;
                m_info.Visible = true;
            }

            // image
            if (!string.IsNullOrEmpty(person.ImageUrl))
            {
                var finalUri = string.Format("https://usercontent.googleapis.com/freebase/v1/image/{0}?maxwidth={1}&maxheight={2}",
                    person.Id,
                    m_pic.Width,
                    m_pic.Height);
                m_pic.Image = ImageManager.Instance.getImage(finalUri);
            }
            else
            {
                var finalUri = string.Format("https://usercontent.googleapis.com/freebase/v1/image/06l46n?maxwidth={0}&maxheight={1}",
                    m_pic.Width,
                    m_pic.Height);
                m_pic.Image = ImageManager.Instance.getImage(finalUri);
            }


            // dinstinct roles

            var roles = Services.EntityManager.GetLookup(LookupType.Role);
            var personRoles = person.Roles.Select(e => e.RoleId).Distinct();
            var relevant = roles.Where(r => personRoles.Contains(r.Id));

            m_distinctRoles.Text = String.Join(" | ", relevant.Select(r => r.Name));

            // roles list
            m_roles.Text = "";
            foreach (var role in relevant)
            {
                var programsForRoles = person.Roles.
                    Where(r => r.RoleId == role.Id).
                    Select(r => r.ProgramName);
                var roleLine = string.Format("{0}: {1}\n", role.Name, string.Join(", ", programsForRoles));
                m_roles.Text += roleLine;
            }
        }
    }
}
